package com.mgee.netty.server.util;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;


@Slf4j
public class RequestUtil {

    private static final String USER_AGENT = "Mozilla/5.0";



    /**
     * get请求
     * @param url
     * @return
     */
    public static String sendGet(String url, Map<String, String> headers){
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("User-Agent", USER_AGENT);
            // 添加headers到请求中
            if (headers != null && !headers.isEmpty()) {
                headers.forEach((key, value) -> con.setRequestProperty(key, value));
            }
            int responseCode = con.getResponseCode();
            System.out.println("GET Response Code :: " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                return response.toString();
            } else {
                throw new RuntimeException("GET request failed with error code : " + responseCode);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static String postJsonContent(String url, Map<String, Object> mapRequest, Map<String, Object> headers) throws Exception {
        log.info("postJsonContent url:{}, mapRequest:{}, headers:{}", url, mapRequest, headers);

        PostMethod method = new PostMethod(url);
        HttpClient httpClient = new HttpClient();
        try {
            RequestEntity entity = new StringRequestEntity(JSON.toJSONString(mapRequest),"application/json","UTF-8");
            method.setRequestEntity(entity);

            // 设置自定义的HTTP头
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, Object> entry : headers.entrySet()) {
                    method.addRequestHeader(entry.getKey(), entry.getValue().toString());
                }
            }


            httpClient.executeMethod(method);
            InputStream in = method.getResponseBodyAsStream();
            //下面将stream转换为String
            StringBuffer sb = new StringBuffer();
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            char[] b = new char[4096];
            for(int n; (n = isr.read(b)) != -1;) {
                sb.append(new String(b, 0, n));
            }
            String returnStr = sb.toString();
            log.info("postJsonContent headers:{}, returnStr:{}", JSON.toJSONString(headers), returnStr);
            return returnStr;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            method.releaseConnection();
        }
    }




}